package Reunion;
use Mojo::Base 'Mojolicious';

use EV;
use DBIx::Custom;
use DBIx::Connector;
use Mango;
use Mojo::JSON;
use Mojo::ByteStream 'b';
use Mojolicious::Validator;
use Mojolicious::Validator::Validation;

has dbh => sub {
    my $self = shift;
    my $appConfig =  $self->plugin('Config' => {'file' => 'config/app.conf'});;
    my $dbConfig = $self->plugin('Config' => {'file' => 'config/db.conf'});;

    my $connector = DBIx::Connector->new(
        'dbi:'.$appConfig->{'db'}.':dbname='.$dbConfig->{$appConfig->{'db'}}->{'dbname'}.';host='.$dbConfig->{$appConfig->{'db'}}->{'host'}.';port='.$dbConfig->{$appConfig->{'db'}}->{'port'},
        $dbConfig->{$appConfig->{'db'}}->{'username'},
        $dbConfig->{$appConfig->{'db'}}->{'password'},
        {
            %{$dbConfig->{$appConfig->{'db'}}->{'options'}}
        }
    );
    my $dbi = DBIx::Custom->connect(connector => $connector);
    my $dbcustom = $dbi->async_conf({prepare_attr => {async=>1}, fh => sub {shift->dbh->mysql_fd}}); 
    return $dbcustom;
};

sub startup {
    my $self = shift;

    my ($sec, $min, $hr, $day, $mon, $year) = localtime;
    printf("%04d-%02d-%02d %02d:%02d:%02d\n", $year+1900, $mon+1, $day, $hr, $min, $sec);

    $self->secrets(['reunion-client-portal']);
    $self->plugin('PODRenderer');
    $self->plugin('AccessControl');

    my $appConfig = $self->plugin('Config' => {'file' => 'config/app.conf'});

    # development and production mode, defined in app.conf
    $self->app->mode($appConfig->{'mode'});

    # setting language for site
    my $siteLanguage = '';
    if ($self->session('defaultLanguage')) {
        $siteLanguage = $self->session->{'defaultLanguage'};
    } else {
        $siteLanguage = $appConfig->{'defaultLanguage'};
        $self->session->{'defaultLanguage'} = $siteLanguage;
    }
#    $self->session->{'languages'} = $appConfig->{'languages'};

    $self->plugin('Charset' => {'charset' => $appConfig->{'charset'}});
    $self->plugin('I18N' => {namespace=>'Reunion::I18N', no_header_detect=>1, default=>$siteLanguage});
    $self->plugin('Human' => {money_delim=>',', money_digit=>' ', datetime=>'%Y-%m-%d %H:%M:%S', time=>'%H:%M:%S', date=>'%Y-%m-%d', phone_country=>8, phone_region=>123});

    # setting mail config
    my $mailConfig = $self->plugin('Config' => {'file' => 'config/mail.conf'});
#    $self->plugin('Mail' => {'from'=>'reunion@pactera.com', 'type'=>'text/html', 'how'=>'sendmail', 'howargs'=>['/usr/sbin/sendmail -t']});
    $self->plugin('Mail' => {'from' => $mailConfig->{'smtp_from'},
                             'type' => $mailConfig->{'smtp_type'},
                             'how' => 'smtp',
                             'howargs'=>[$mailConfig->{'smtp_server'},
                                         'AuthUser' => $mailConfig->{'smtp_user'},
                                         'AuthPass' => $mailConfig->{'smtp_password'}]});

    # setting db config
    my $dbConfig = $self->plugin('Config' => {'file' => 'config/db.conf'});
    state $mango = Mango->new('mongodb://'.$dbConfig->{'mongodb'}->{'host'}.':'.$dbConfig->{'mongodb'}->{'port'});
    my $oid = $mango->db($dbConfig->{'mongodb'}->{'dbname'});
    $self->app->helper('mongodb' => sub {$oid});

    $self->hook(after_dispatch => sub {
        my $self = shift;
        $self->res->headers->header('Access-Control-Allow-Methods' => 'POST, GET, OPTIONS');
    });

    my $validator = Mojolicious::Validator->new;
    $validator->add_check('check_point' => sub {
        my ($validation, $name, $value, $self) = @_;
    });
    my $validation = Mojolicious::Validator::Validation->new(validator => $validator);
    $self->app->helper('validation' => sub {$validation});

    ##################### global function start ############################
    $self->app->helper('jsonEncode' => sub {
        my $self = shift;
        my $param = shift;# array ref or hash ref
        my $json = Mojo::JSON->new;
        return b($json->encode($param))->decode('UTF-8');
    });
    $self->app->helper('getUrl' => sub {
        my $self = shift;
        my $hosturl = $self->req->url->base;
        my $url = Mojo::URL->new($hosturl->scheme.'://'.$hosturl->host.'/');
        my $current_url = $url->to_abs;
        return $current_url;
    });
    $self->app->helper('getTable' => sub {
        my $self = shift;
        my $tableName = shift;
    });
    ##################### global function end ############################

    ##################### route info start ############################
    my $r = $self->routes;
    my $route = $r->bridge('/')->to(cb => sub {
        my $self = shift;
        # Authenticated
        if ($self->session('userInfo')) {
            # get controller and action name
            my $routepoint = $self->match->stack->[-1];
            my @controllers = split('-', $routepoint->{'controller'});
            my $pathname = {'namespace'=>$controllers[0], 'controller'=>$controllers[1], 'action'=>$routepoint->{'action'}};
            $self->session->{'pathname'} = $pathname;
            return 1;
        }
        # Not authenticated
        $self->redirect_to('/login');
        return undef;
    });
    # Normal route to controller#action
    $r->get('/login')->to('user-user#showlogin');
    $r->post('/login')->to('user-user#login');
    $route->get('/')->to('user-user#index');
    $route->get('/logout')->to('user-user#logout');
    $route->get('/user')->to('user-user#index');
    $route->get('/resource')->to('user-resource#index');
    $route->post('/resource/add')->to('user-resource#add');
    $route->put('/resource/update/:id' => [id=>qr/\d+/])->to('user-resource#update');
    ##################### route info end ############################
}









1;